﻿using ExcelUnity.Exporter.Exporters;
using System.Collections.Generic;
using System.Linq;

namespace ExcelUnity.Exporter.Wrappers.SheetWrapperBuilders
{
    public class DynamicTypeBuilder : BaseBuilder
    {
        private List<IDictionary<string, object>> SourceList = new List<IDictionary<string, object>>();

        public override List<ColumnAdapter> BuildColumnAdapter(ExportSheet sheet)
        {
            if (sheet.Data!.Count == 0) return null;

            var columns = new Dictionary<int, string>();


            var colIndex = 0;
            foreach (IDictionary<string, object> row in sheet.Data!)
            {
                foreach (var item in row)
                {
                    if (!columns.ContainsValue(item.Key))
                        columns.Add(colIndex++, item.Key);
                }
                SourceList.Add(row);
            }

            var columnAdapters = sheet.ToAdapters(columns);
            return columnAdapters;
        }

        public override IEnumerable<ExportRowWrapper> FillDataRows(ExportSheet sheet, List<ColumnAdapter> columnAdapters, int rowIndex)
        {
            var colAdapterDic = columnAdapters.ToDictionary(x => x.ColumnIndex);
            foreach (var row in SourceList)
            {
                var cells = new List<ExportCellWrapper>();
                foreach (var adapter in columnAdapters)
                {
                    row.TryGetValue(adapter.Name, out object cellValueObj);
                    var val = cellValueObj?.ToString();

                    var cell = new ExportCellWrapper(val, adapter);
                    if (adapter.SpecialCellStyle?.ContainsKey(val) ?? false)
                        cell.CellStyle = adapter.SpecialCellStyle[val];

                    cells.Add(cell);
                }

                yield return new ExportRowWrapper(cells, rowIndex++);
            }
        }
    }
}
